package com.example.onlinemonitoring.Util.tem;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.ConditionDispose;
import com.example.onlinemonitoring.Util.DefaultProperty;
import com.example.onlinemonitoring.Util.DefaultPropertyByInsert;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.dao.RepointaddrMapper;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.common.MyResult;
import com.example.onlinemonitoring.model.common.addrinfo;
import com.example.onlinemonitoring.model.common.alarmmessage;
import com.example.onlinemonitoring.model.common.chartres;
import com.example.onlinemonitoring.model.common.pagebase;
import com.example.onlinemonitoring.model.common.repointaddr;
import com.example.onlinemonitoring.model.common.sensor;
import com.example.onlinemonitoring.model.common.series;
import com.example.onlinemonitoring.query.QueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.apache.ibatis.session.RowBounds;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import com.example.onlinemonitoring.Util.LanguageManager;

/**
 * Created by rongyaowen
 * on 2022/4/3.
 * <p>
 * 抽象service实现，实现了基础mapper的基础方法，所有需要基础mapper的service实现类继承这个类
 */
public abstract class SensorAbstractBaseService<T extends sensor, K extends sensor> extends AbstractBaseService<T> {
    @Autowired
    LanguageManager languageManager;
    @Autowired
    protected MyMapper<K> hisMapper;
    @Autowired
    private RepointaddrMapper RepointaddrMapper;
    private Class<T> modelClass;// 当前泛型的真实类型Class
    private Class<K> modelKClass;// 当前泛型的真实类型Class

    @SuppressWarnings("unchecked")
    public SensorAbstractBaseService() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
        ParameterizedType ptk = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelKClass = (Class<K>) ptk.getActualTypeArguments()[0];
    }

    public T getModel(T record) {
        return selectOneByExample(ConditionDispose.defaultDisposeByUpdate(record, record.getClass()));
    }

    public T getModel(DefaultPropertyByInsert record) {
        return selectOneByExample(ConditionDispose.defaultDisposeByInUse(record, modelClass));
    }

    public T getFirst(T record) {
        Example example = new Example(modelClass);
        Example.Criteria criteria = example.createCriteria();
        ConditionDispose.defaultDisposeByUpdate(criteria, ConditionDispose.copy(record));
        RowBounds rb = new RowBounds(0, 1);
        List<T> list = selectByExampleAndRowBounds(example, rb);
        if (list.size() != 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    public K getHisModel(K record) {
        return hisMapper.selectOneByExample(ConditionDispose.defaultDisposeByInUse(record, modelKClass));
    }

    public int Delete(T record) {
        if (deleteByExample(ConditionDispose.defaultDispose(record, record.getClass())) != 0)
            return 1;
        else
            return 0;
    }

    public int DeleteByClass(DefaultProperty record) {
        if (deleteByExample(ConditionDispose.defaultDispose(record, modelClass)) != 0)
            return 1;
        else
            return 0;
    }

    /**
     * 根据Appdevice的stationid和devicegroup参数删除
     * 
     * @param ad
     * @return
     */
    public int Delete(Appdevice ad) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(ad.getStationid());
        record.setDevicegroup(ad.getDevicegroup());
        return DeleteByClass(record);
    }

    /**
     * 删除所有
     * 
     * @return
     */
    public int Delete() {
        if (DeleteByClass(new DefaultProperty()) != 0)
            return 1;
        else
            return 0;
    }

    /**
     * 添加监测点
     * 
     * @param record
     * @return
     */
    public int Add(Appdevice record) {
        int ret = 1;
        for (int i = record.getAddrmin(); i < record.getAddrmax() + 1; i++) {
            Example example = new Example(modelClass);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("stationid", record.getStationid());
            criteria.andEqualTo("devicegroup", record.getDevicegroup());
            criteria.andEqualTo("deviceaddr", i);
            if (record.getPointcount() != null) {
                for (int j = 1; j <= record.getPointcount(); j++) {
                    criteria.andEqualTo("pointaddr", j);
                    DefaultPropertyByInsert sensor = new DefaultPropertyByInsert();
                    sensor.setAddrname(i + "#主变");
                    sensor.setPointname(i + "-" + j);
                    sensor.setDeviceaddr(i);
                    sensor.setPointaddr(j);
                    sensor.setStationid(record.getStationid());
                    sensor.setDevicegroup(record.getDevicegroup());
                    sensor.setLastcommunicationstatus(-1);
                    sensor.setLastdatatime(new Date());
                    sensor.setLastalarmlevel(0);
                    sensor.setLastalarmmessage("");
                    sensor.setMemo("");
                    sensor.setInuse(1);
                    T t = newTclass(modelClass);
                    BeanUtils.copyProperties(sensor, t);
                    if (selectOneByExample(example) == null) {
                        if (insertSelective(t) == 0) {
                            ret = 0;
                        }
                    }
                }
            } else {
                DefaultPropertyByInsert sensor = new DefaultPropertyByInsert();
                sensor.setPointname(languageManager.getLan().getNewMonitoringPoint());
                sensor.setDeviceaddr(i);
                sensor.setStationid(record.getStationid());
                sensor.setDevicegroup(record.getDevicegroup());
                sensor.setLastcommunicationstatus(-1);
                sensor.setLastdatatime(new Date());
                sensor.setLastalarmlevel(0);
                sensor.setLastalarmmessage("");
                sensor.setMemo("");
                if (record.getSimple().equals("gispd") && record.getBrand().equals("西电")) {
                    sensor.setStyle(
                            "dischargetype|1|放电类型,dcp|1|放电概率,daver|1|放电均值,rst|1|上次放电次数,dischargeamount|1|放电峰值(dBm),phase|1|相位(度)");
                    // sensor.setStyle61850("H2O|DGA1/SIML%s.H2O.mag.f,H2ppm|DGA1/SIML%s.H2ppm.mag.f,COppm|DGA1/SIML%s.COppm.mag.f,H2OFrmRate|DGA1/SIML%s.H2OFrmRate.mag.f,H2FrmRate|DGA1/SIML%s.H2FrmRate.mag.f,COFrmRate|DGA1/SIML%s.COFrmRate.mag.f");
                } else if (record.getBrand().equals("DGA3")) {
                    sensor.setStyle(
                            "ppm|1|油内湿度H2O(ppm),h2|1|氢气H2(ppm),co|1|一氧化碳CO(ppm)");
                    sensor.setStyle61850(
                            "H2O|DGA1/SIML%s.H2O.mag.f,H2ppm|DGA1/SIML%s.H2ppm.mag.f,COppm|DGA1/SIML%s.COppm.mag.f");
                }
                sensor.setInuse(1);
                T t = newTclass(modelClass);
                BeanUtils.copyProperties(sensor, t);
                if (selectOneByExample(example) == null) {
                    if (insertSelective(t) == 0) {
                        ret = 0;
                    }
                }
            }
        }
        return ret;
    }

    /**
     * 更新实时表
     * 
     * @param record
     * @param byid
     * @return
     */
    public int Update(T record, boolean byid) {
        if (byid)
            return updateByPrimaryKeySelective(record);
        else
            return updateByExampleSelective(record, ConditionDispose.defaultDisposeByUpdate(record, record.getClass()));
    }

    /**
     * 插入历史表
     * 
     * @param record
     * @return
     */
    public int Add(K record) {
        return hisMapper.insertSelective(record);
    }

    public int updatehis(K record) {
        return hisMapper.updateByExampleSelective(record,
                ConditionDispose.defaultDisposeByUpdate(record, record.getClass()));
    }

    /**
     * 查询分页实时表
     * 
     * @param record
     * @param qo
     * @return
     */
    public MyResult<T> getList(T record, QueryObject qo) {
        if (qo.getPage() != null || qo.getLimit() != null) {
            PageHelper.startPage(qo.getPage(), qo.getLimit());
        }
        List<T> list = selectByExample(ConditionDispose.defaultDispose(record, record.getClass()));
        MyResult<T> result = new MyResult<T>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            if (qo.getPage() != null || qo.getLimit() != null) {
                PageInfo<T> pi = new PageInfo<>(list);
                result.setCount((int) pi.getTotal());
            } else {
                result.setCount(list.size());
            }
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    /**
     * 查询分页实时表，有排除项
     * 
     * @param record
     * @param qo
     * @return
     */
    public MyResult<T> getList(T record, QueryObject qo, String... properties) {
        if (qo.getPage() != null || qo.getLimit() != null) {
            PageHelper.startPage(qo.getPage(), qo.getLimit());
        }
        List<T> list = selectByExample(ConditionDispose.defaultDispose(record, record.getClass(), properties));
        MyResult<T> result = new MyResult<T>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            if (qo.getPage() != null || qo.getLimit() != null) {
                PageInfo<T> pi = new PageInfo<>(list);
                result.setCount((int) pi.getTotal());
            } else {
                result.setCount(list.size());
            }
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    /**
     * 查询实时表
     * 
     * @param record
     * @return
     */
    public MyResult<T> getList(T record) {
        List<T> list = selectByExample(ConditionDispose.defaultDispose(record, record.getClass()));
        MyResult<T> result = new MyResult<T>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(list != null && !list.isEmpty() ? list.size() : 0);
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    /**
     * 查询所有记录
     * 
     * @param record
     * @return
     */
    public MyResult<T> getAllList() {
        List<T> list = selectAll();
        MyResult<T> result = new MyResult<T>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(list != null && !list.isEmpty() ? list.size() : 0);
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    /**
     * 查询实时表(不封装)
     * 
     * @param record
     * @return
     */
    public List<T> getLists(T record) {
        return selectByExample(ConditionDispose.defaultDispose(record, record.getClass()));
    }

    /**
     * 查询分页实时表(不封装)
     * 
     * @param record
     * @return
     */
    public List<T> getLists(T record, QueryObject qo) {
        if (qo.getPage() != null || qo.getLimit() != null) {
            PageHelper.startPage(qo.getPage(), qo.getLimit());
        }
        return selectByExample(ConditionDispose.defaultDispose(record, record.getClass()));
    }

    /**
     * 查询实时表(设备组)
     * 
     * @param record
     * @return
     */
    public List<T> getLists(T record, Integer groupstart, Integer groupend) {
        return selectByExample(ConditionDispose.defaultDispose(record, record.getClass(), groupstart, groupend));
    }

    /**
     * 查询历史表
     * 
     * @param record
     * @param pageBase
     * @return
     */
    public MyResult<K> getHisList(K record, pagebase pageBase) {
        List<K> list = new ArrayList<>();
        PageHelper.startPage(pageBase.getPage(), pageBase.getLimit());
        Example example = ConditionDispose.defaultDisposeByHistory(record, record.getClass(), pageBase);
        list = hisMapper.selectByExample(example);
        int countNums;
        if (pageBase.getPagecount() != null) {
            PageInfo<K> hpi = new PageInfo<>(list);
            // 获取当前页数据是否超过总查询条数
            int list_size = pageBase.getPage() * pageBase.getLimit() - pageBase.getPagecount();
            if (list_size > 0 && list_size < list.size()) {
                // 删除多余的查询条数
                list = list.subList(0, list.size() - list_size);
            }
            countNums = (int) hpi.getTotal() > pageBase.getPagecount() ? pageBase.getPagecount() : (int) hpi.getTotal();
        } else {
            PageInfo<K> hpi = new PageInfo<>(list);
            countNums = (int) hpi.getTotal();
        }
        MyResult<K> result = new MyResult<K>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(countNums);
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    /**
     * 查询历史表，通过id查询
     * 
     * @param record
     * @param pageBase
     * @return
     */
    public MyResult<K> getHisListById(K record, pagebase pageBase, Integer id) {
        List<K> list = new ArrayList<>();
        PageHelper.startPage(pageBase.getPage(), pageBase.getLimit());
        Example example = ConditionDispose.defaultDisposeByHistoryId(record, record.getClass(), pageBase, id);
        list = hisMapper.selectByExample(example);
        int countNums;
        if (pageBase.getPagecount() != null) {
            PageInfo<K> hpi = new PageInfo<>(list);
            // 获取当前页数据是否超过总查询条数
            int list_size = pageBase.getPage() * pageBase.getLimit() - pageBase.getPagecount();
            if (list_size > 0 && list_size < list.size()) {
                // 删除多余的查询条数
                list = list.subList(0, list.size() - list_size);
            }
            countNums = (int) hpi.getTotal() > pageBase.getPagecount() ? pageBase.getPagecount() : (int) hpi.getTotal();
        } else {
            PageInfo<K> hpi = new PageInfo<>(list);
            countNums = (int) hpi.getTotal();
        }
        MyResult<K> result = new MyResult<K>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(countNums);
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    /**
     * 查询历史表
     * 
     * @param record
     * @param pageBase
     * @return
     */
    public MyResult<K> getHisList(K record, pagebase pageBase, String... properties) {
        List<K> list = new ArrayList<>();
        PageHelper.startPage(pageBase.getPage(), pageBase.getLimit());
        Example example = ConditionDispose.defaultDisposeByHistory(record, record.getClass(), pageBase, properties);
        list = hisMapper.selectByExample(example);
        int countNums;
        if (pageBase.getPagecount() != null) {
            PageInfo<K> hpi = new PageInfo<>(list);
            // 获取当前页数据是否超过总查询条数
            int list_size = pageBase.getPage() * pageBase.getLimit() - pageBase.getPagecount();
            if (list_size > 0 && list_size < list.size()) {
                // 删除多余的查询条数
                list = list.subList(0, list.size() - list_size);
            }
            countNums = (int) hpi.getTotal() > pageBase.getPagecount() ? pageBase.getPagecount() : (int) hpi.getTotal();
        } else {
            PageInfo<K> hpi = new PageInfo<>(list);
            countNums = (int) hpi.getTotal();
        }
        MyResult<K> result = new MyResult<K>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(countNums);
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    /**
     * 查询历史表
     * 
     * @param record
     * @param pageBase
     * @return
     */
    public List<K> getNoResultHisList(K record, pagebase pageBase) {
        List<K> list = new ArrayList<>();
        PageHelper.startPage(pageBase.getPage(), pageBase.getLimit());
        Example example = ConditionDispose.defaultDisposeByHistory(record, record.getClass(), pageBase);
        list = hisMapper.selectByExample(example);
        int countNums;
        if (pageBase.getPagecount() != null) {
            PageInfo<K> hpi = new PageInfo<>(list);
            // 获取当前页数据是否超过总查询条数
            int list_size = pageBase.getPage() * pageBase.getLimit() - pageBase.getPagecount();
            if (list_size > 0 && list_size < list.size()) {
                // 删除多余的查询条数
                list = list.subList(0, list.size() - list_size);
            }
            countNums = (int) hpi.getTotal() > pageBase.getPagecount() ? pageBase.getPagecount() : (int) hpi.getTotal();
        } else {
            PageInfo<K> hpi = new PageInfo<>(list);
            countNums = (int) hpi.getTotal();
        }
        return list;
    }

    /**
     * 获取历史表曲线
     * 
     * @param record
     * @param lstr
     * @param pageBase
     * @return
     */
    public MyResult<chartres> getHisCurveList(K record, String lstr, pagebase pageBase) {
        List<String> legend = new ArrayList<>();
        List<String> columns = new ArrayList<>();
        DefaultPropertyByInsert table = new DefaultPropertyByInsert();
        DefaultProperty table1 = new DefaultProperty();
        BeanUtils.copyProperties(record, table1);
        table.setStationid(table1.getStationid());
        table.setDevicegroup(table1.getDevicegroup());
        table.setDeviceaddr(table1.getDeviceaddr());
        table.setPointaddr(table1.getPointaddr());
        T t = newTclass(modelClass);
        BeanUtils.copyProperties(table, t);
        t = getModel(t);
        if (t == null) {
            return new MyResult<chartres>(1, "曲线图查询失败！地址" + table.getDeviceaddr() + "不存在！");
        }
        BeanUtils.copyProperties(t, table);
        String[] leg = table.getStyle().split(",");
        if (lstr == null) {
            for (int i = 0; i < leg.length; i++) {
                if (leg[i].split("\\|")[1].equals("1")) {
                    String[] ls = leg[i].split("\\|");
                    if (getValueType("last" + ls[0], t)) {
                        legend.add(ls[2]);
                        columns.add(ls[0]);
                    }
                }
            }
        } else {
            String[] lstrs = lstr.split(",");
            for (int i = 0; i < leg.length; i++) {
                for (int j = 0; j < lstrs.length; j++) {
                    if (leg[i].split("\\|")[0].equals(lstrs[j])) {
                        String[] ls = leg[i].split("\\|");
                        if (getValueType("last" + ls[0], t)) {
                            legend.add(ls[2]);
                            columns.add(ls[0]);
                        }
                    }
                }
            }
        }
        List<K> list = new ArrayList<>();
        PageHelper.startPage(pageBase.getPage(), pageBase.getLimit());
        Example example = ConditionDispose.defaultDisposeByHistory(record, record.getClass(), pageBase);
        list = hisMapper.selectByExample(example);
        if (pageBase.getPagecount() != null) {
            int list_size = pageBase.getPage() * pageBase.getLimit() - pageBase.getPagecount();
            if (list_size > 0 && list_size < list.size()) {
                // 删除多余的查询条数
                list = list.subList(0, list.size() - list_size);
            }
        }
        Collections.reverse(list);
        chartres cts = new chartres();
        cts.setLegend(legend);
        int len = cts.getLegend().size();
        int llen = list.size();
        String[] dt = new String[llen];
        float[][] sres = new float[len][llen];
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM ddHH:mm:ss 'GMT'XXX yyyy", Locale.US);
        SimpleDateFormat csdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < cts.getLegend().size(); j++) {
                String s = getValue(columns.get(j), list.get(i));
                if (s != null && !s.equals(""))
                    sres[j][i] = Float.parseFloat(s);
            }
            try {
                if (CommPortManager.isnull(getValue("datatime", list.get(i))).contains("CST")) {
                    dt[i] = sdf2.format(csdf.parse(getValue("datatime", list.get(i))));
                } else if (CommPortManager.isnull(getValue("datatime", list.get(i))).contains("GMT")) {
                    dt[i] = sdf2.format(sdf.parse(getValue("datatime", list.get(i))));
                } else {
                    dt[i] = sdf2.format(csdf.parse(getValue("datatime", list.get(i))));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        cts.setDt(dt);
        for (int j = 0; j < len; j++) {
            String ename = columns.get(j);
            cts.getSerieslist().add(new series(cts.getLegend().get(j), 1, "line", ename, sres[j]));
        }
        List<chartres> chlist = new ArrayList<>();
        chlist.add(cts);
        MyResult<chartres> result = new MyResult<chartres>();
        if (cts.getSerieslist().size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(cts.getSerieslist().size());
            result.setData(chlist);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    /**
     * 获取所有在运行的设备总条数
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getTotalCount(int stationid, int devicegroup) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setInuse(1);
        return selectCountByExample(ConditionDispose.defaultDisposeByInUse(record, modelClass));
    }

    /**
     * 获取报警中的设备总条数
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getAlarmCount(int stationid, int devicegroup) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setInuse(1);
        record.setLastalarmlevel(2);
        return selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
    }

    /**
     * 获取预警中的设备总条数
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getWarnCount(int stationid, int devicegroup) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setInuse(1);
        record.setLastalarmlevel(1);
        return selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
    }

    /**
     * 获取通讯正常的（不判断报警不报警）设备总条数
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getNormalCount(int stationid, int devicegroup) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setInuse(1);
        record.setLastcommunicationstatus(0);
        return selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
    }

    /**
     * 获取通讯异常的（不判断报警不报警）设备总条数
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getAbnormalCount(int stationid, int devicegroup) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setInuse(1);
        record.setLastcommunicationstatus(1);
        int abcount1 = selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
        record.setLastcommunicationstatus(-1);
        int abcount2 = selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
        return abcount1 + abcount2;
    }

    /**
     * 获取所有在运行的单个设备
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getTotalCount(int stationid, int devicegroup, int deviceaddr, int pointaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setDeviceaddr(deviceaddr);
        record.setPointaddr(pointaddr);
        record.setInuse(1);
        return selectCountByExample(ConditionDispose.defaultDisposeByInUse(record, modelClass));
    }

    /**
     * 获取报警中的单个设备
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getAlarmCount(int stationid, int devicegroup, int deviceaddr, int pointaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setDeviceaddr(deviceaddr);
        record.setPointaddr(pointaddr);
        record.setInuse(1);
        record.setLastalarmlevel(2);
        return selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
    }

    /**
     * 获取预警中的单个设备
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getWarnCount(int stationid, int devicegroup, int deviceaddr, int pointaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setDeviceaddr(deviceaddr);
        record.setPointaddr(pointaddr);
        record.setInuse(1);
        record.setLastalarmlevel(1);
        return selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
    }

    /**
     * 获取通讯正常的（不判断报警不报警）单个设备
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getNormalCount(int stationid, int devicegroup, int deviceaddr, int pointaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setDeviceaddr(deviceaddr);
        record.setPointaddr(pointaddr);
        record.setInuse(1);
        record.setLastcommunicationstatus(0);
        return selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
    }

    /**
     * 获取通讯异常的（不判断报警不报警）单个设备
     * 
     * @param stationid
     * @param devicegroup
     * @return
     */
    public int getAbnormalCount(int stationid, int devicegroup, int deviceaddr, int pointaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setDeviceaddr(deviceaddr);
        record.setPointaddr(pointaddr);
        record.setInuse(1);
        record.setLastcommunicationstatus(1);
        int abcount1 = selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
        record.setLastcommunicationstatus(-1);
        int abcount2 = selectCountByExample(ConditionDispose.alarmDispose(record, modelClass));
        return abcount1 + abcount2;
    }

    /**
     * 更新运行状态
     * 
     * @param ad
     * @param addr
     * @param b
     */
    public void UpdateStatus(Appdevice ad, Integer addr, int b) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(ad.getStationid());
        record.setDevicegroup(ad.getDevicegroup());
        record.setLastcommunicationstatus(b);
        record.setDeviceaddr(addr);
        T t = newTclass(modelClass);
        BeanUtils.copyProperties(record, t);
        Update(t, false);
    }

    /**
     * 更新通讯状态，所有地址
     * 
     * @param ad
     * @param addr
     * @param b
     */
    public void UpdateStatus(Appdevice ad, int b) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(ad.getStationid());
        record.setDevicegroup(ad.getDevicegroup());
        record.setLastcommunicationstatus(b);
        T t = newTclass(modelClass);
        BeanUtils.copyProperties(record, t);
        Update(t, false);
    }

    public List<alarmmessage> getAlarmmessageList(Appdevice ad) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<alarmmessage> list = new ArrayList<>();
        Example example = new Example(modelClass);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", ad.getStationid());
        criteria.andEqualTo("devicegroup", ad.getDevicegroup());
        if (getField("inuse", modelClass)) {
            criteria.andEqualTo("inuse", 1);
        }
        if (getField("lastalarmlevel", modelClass)) {
            criteria.andNotEqualTo("lastalarmlevel", 0);
        }
        List<T> sensorlist = selectByExample(example);
        for (int i = 0; i < sensorlist.size(); i++) {
            String lastcommunicationstatus = getValue("lastcommunicationstatus", sensorlist.get(i));
            String pointaddr = getValue("pointaddr", sensorlist.get(i));
            String lastalarmlevel = getValue("lastalarmlevel", sensorlist.get(i));
            String lastalarmmessage = getValue("lastalarmmessage", sensorlist.get(i));
            String dtt = getTValue("lastdatatime", sensorlist.get(i));
            String dt = "";
            if (ad.getSimple().equals("arcxx"))
                dt = dtt;
            else
                dt = sdf.format(new Date());
            alarmmessage am = new alarmmessage(sensorlist.get(i).getStationid(),
                    sensorlist.get(i).getDevicegroup(),
                    sensorlist.get(i).getDeviceaddr(),
                    Integer.valueOf(HexUtil.isnullToInteger(pointaddr)),
                    ad.getName(),
                    ad.getEname(),
                    sensorlist.get(i).getPointname(),
                    Integer.valueOf(HexUtil.isnullToInteger(lastcommunicationstatus)),
                    dt,
                    Integer.valueOf(HexUtil.isnullToInteger(lastalarmlevel)),
                    HexUtil.isnull(lastalarmmessage));
            list.add(am);
        }
        return list;
    }

    /**
     * 移动端获取报警设备
     * 
     * @param ad
     * @return
     */
    public int getAlarmCount(Appdevice ad) {
        Example example = new Example(modelClass);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", ad.getStationid());
        criteria.andEqualTo("devicegroup", ad.getDevicegroup());
        if (getField("inuse", modelClass)) {
            criteria.andEqualTo("inuse", 1);
        }
        if (getField("lastalarmlevel", modelClass)) {
            criteria.andNotEqualTo("lastalarmlevel", 0);
        }
        return selectCountByExample(example);
    }

    /**
     * 
     * @param t
     * @return
     */
    public List<T> SelectAlarm(T t) {
        return selectByExample(ConditionDispose.defaultDisposeByInUse(t, modelClass));
    }

    /**
     * 通过反射获取实时表字段的值
     *
     * @param field 字段
     * @param t     对象
     * @param <T>
     * @return
     */
    protected static <T> String getValue(String field, T t) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                if (descriptor.getName().equals(field)) {
                    if (descriptor.getReadMethod().invoke(t) != null)
                        return descriptor.getReadMethod().invoke(t).toString();
                }
            }
        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过反射获取历史表字段的值
     *
     * @param field 字段
     * @param k     对象
     * @param <K>
     * @return
     */
    protected String getKValue(String field, K k) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(k.getClass());
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                if (descriptor.getName().equals(field)) {
                    String retvalue = myCustomName(field,
                            descriptor.getReadMethod().invoke(k) != null
                                    ? descriptor.getReadMethod().invoke(k).toString()
                                    : "");
                    if (retvalue != null && !retvalue.equals("")) {// 自定义的返回值表达形式
                        return retvalue;
                    }
                    if (descriptor.getReadMethod().invoke(k) != null) {
                        if (Date.class.isAssignableFrom(descriptor.getReadMethod().getReturnType())) {// 日期格式化
                            try {
                                return HexUtil.stosdate(descriptor.getReadMethod().invoke(k).toString());
                            } catch (IllegalArgumentException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (ParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            ;
                        } else {
                            return descriptor.getReadMethod().invoke(k).toString();
                        }
                    }
                }
            }
        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过反射获取历史表字段的值
     *
     * @param field 字段
     * @param k     对象
     * @param <K>
     * @return
     */
    protected String getTValue(String field, T t) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                if (descriptor.getName().equals(field)) {
                    String retvalue = myCustomName(field,
                            descriptor.getReadMethod().invoke(t) != null
                                    ? descriptor.getReadMethod().invoke(t).toString()
                                    : "");
                    if (retvalue != null && !retvalue.equals("")) {// 自定义的返回值表达形式
                        return retvalue;
                    }
                    if (descriptor.getReadMethod().invoke(t) != null) {
                        if (Date.class.isAssignableFrom(descriptor.getReadMethod().getReturnType())) {// 日期格式化
                            try {
                                return HexUtil.stosdate(descriptor.getReadMethod().invoke(t).toString());
                            } catch (IllegalArgumentException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (ParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            ;
                        } else {
                            return descriptor.getReadMethod().invoke(t).toString();
                        }
                    }
                }
            }
        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected String myCustomName(String field, String string) {
        return "";
    }

    /**
     * 判断字段是否是整数或浮点数
     *
     * @param field 字段
     * @param t     对象
     * @param <T>
     * @return
     */
    private static <T> Boolean getValueType(String field, T t) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                if (descriptor.getName().equals(field)) {
                    return Long.class.isAssignableFrom(descriptor.getReadMethod().getReturnType()) ||
                            Integer.class.isAssignableFrom(descriptor.getReadMethod().getReturnType()) ||
                            Short.class.isAssignableFrom(descriptor.getReadMethod().getReturnType()) ||
                            BigDecimal.class.isAssignableFrom(descriptor.getReadMethod().getReturnType()) ||
                            Double.class.isAssignableFrom(descriptor.getReadMethod().getReturnType()) ||
                            Float.class.isAssignableFrom(descriptor.getReadMethod().getReturnType());
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断对象是否拥有字段属性
     *
     * @param field 字段
     * @param t     对象
     * @param <T>
     * @return
     */
    private static <T> boolean getField(String field, Class<T> t) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(t);
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                if (descriptor.getName().equals(field)) {
                    return true;
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查找有监测点的设备的地址列表
     * 
     * @param t
     * @return
     */
    public MyResult<addrinfo> SelectAddrInfo(T t) {
        MyResult<addrinfo> m = new MyResult<addrinfo>();
        DefaultProperty defaultProperty = new DefaultProperty();
        BeanUtils.copyProperties(t, defaultProperty);
        defaultProperty.setTableName(modelClass.getSimpleName().toLowerCase());
        List<addrinfo> ts = RepointaddrMapper.selectaddrinfo(defaultProperty);
        m.setData(ts);
        m.setCode(MyResult.SUCCESS);
        m.setMsg("查询成功！");
        return m;
    }

    /**
     * 查找有监测点的设备的inuse关联
     * 
     * @param t
     * @return
     */
    public MyResult<repointaddr> SelectInuse(T t) {
        MyResult<repointaddr> m = new MyResult<repointaddr>();
        DefaultProperty defaultProperty = new DefaultProperty();
        BeanUtils.copyProperties(t, defaultProperty);
        defaultProperty.setTableName(modelClass.getSimpleName().toLowerCase());
        List<repointaddr> ts = RepointaddrMapper.selectinuse(defaultProperty);
        m.setData(ts);
        m.setCode(MyResult.SUCCESS);
        m.setMsg("查询成功！");
        return m;
    }

    /**
     * 更新有监测点的设备的显示和隐藏
     * 
     * @param repointaddr
     * @param stationid
     * @param devicegroup
     * @return
     */
    public MyResult<Integer> UpdateInuse(repointaddr repointaddr, Integer stationid, Integer devicegroup) {
        Example example = new Example(modelClass);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", stationid);
        criteria.andEqualTo("devicegroup", devicegroup);
        criteria.andEqualTo("deviceaddr", repointaddr.getDeviceaddr());
        T t = newTclass(modelClass);
        DefaultProperty defaultProperty = new DefaultProperty();
        defaultProperty.setInuse(0);
        BeanUtils.copyProperties(defaultProperty, t);
        updateByExampleSelective(t, example);
        if (repointaddr.getPointaddrmin() != 0 && repointaddr.getPointaddrmax() != 0) {
            // 将范围内的设备inuse置为1
            criteria.andGreaterThanOrEqualTo("pointaddr", repointaddr.getPointaddrmin());
            criteria.andLessThanOrEqualTo("pointaddr", repointaddr.getPointaddrmax());
            defaultProperty.setInuse(1);
            BeanUtils.copyProperties(defaultProperty, t);
            updateByExampleSelective(t, example);
        }
        return new MyResult<Integer>(true);
    }

    /**
     * 导出历史表Excel
     * 
     * @param record
     * @param pageBase
     * @return
     */
    public Workbook writeToExcelByList(K record, pagebase pageBase) {
        List<String> legend = new ArrayList<>();
        List<String> columns = new ArrayList<>();
        DefaultPropertyByInsert table = new DefaultPropertyByInsert();
        DefaultProperty table1 = new DefaultProperty();
        BeanUtils.copyProperties(record, table1);
        table.setStationid(table1.getStationid());
        table.setDevicegroup(table1.getDevicegroup());
        table.setDeviceaddr(table1.getDeviceaddr());
        table.setPointaddr(table1.getPointaddr());
        T t = newTclass(modelClass);
        BeanUtils.copyProperties(table, t);
        List<T> tlist = getLists(t);
        if (tlist.size() == 0) {
            return new XSSFWorkbook();
        } else {
            t = tlist.get(0);
        }
        BeanUtils.copyProperties(t, table);
        String[] leg = table.getStyle().split(",");
        columns.add("stationid");
        columns.add("devicegroup");
        columns.add("deviceaddr");
        if (table1.getPointaddr() != null) {
            columns.add("pointaddr");
        }
        columns.add("pointname");
        columns.add("datatime");
        legend.add(languageManager.getLan().getStationID());
        legend.add(languageManager.getLan().getDeviceGroup());
        legend.add(languageManager.getLan().getDeviceAddress());
        if (table1.getPointaddr() != null) {
            legend.add(languageManager.getLan().getPointAddress());
        }
        legend.add(languageManager.getLan().getPointName());
        legend.add(languageManager.getLan().getDataTime());
        for (int i = 0; i < leg.length; i++) {
            if (leg[i].split("\\|")[1].equals("1")) {
                String[] ls = leg[i].split("\\|");
                if (getValueType("last" + ls[0], t) || getValueType(ls[0], t)) {
                    legend.add(ls[2]);
                    columns.add(ls[0]);
                }
            }
        }
        columns.add("alarmlevel");
        columns.add("alarmmessage");
        legend.add(languageManager.getLan().getAlarmLevel());
        legend.add(languageManager.getLan().getAlarmDetails());
        List<K> list = new ArrayList<>();
        Example example = ConditionDispose.defaultDisposeByHistory(record, record.getClass(), pageBase);
        list = hisMapper.selectByExample(example);

        // 创建工作薄
        Workbook wb = new XSSFWorkbook();
        // 标题和页码
        CellStyle titleStyle = wb.createCellStyle();
        // 设置单元格对齐方式,水平居左
        titleStyle.setAlignment(HorizontalAlignment.LEFT);
        // 设置字体样式
        Font titleFont = wb.createFont();
        // 字体高度
        titleFont.setFontHeightInPoints((short) 12);
        // 字体样式
        titleFont.setFontName("黑体");
        titleStyle.setFont(titleFont);
        // 创建sheet
        Sheet sheet = wb.createSheet(languageManager.getLan().getHistoricalDetails());
        // 自动设置宽度
        sheet.autoSizeColumn(0);

        // 在sheet中添加标题行// 行数从0开始
        Row row = sheet.createRow((int) 0);
        for (int i = 0; i < legend.size(); i++) {
            if (legend.get(i).equals(languageManager.getLan().getDataTime())) {
                sheet.setColumnWidth(i, 5000);
            }
            Cell cell = row.createCell(i);
            cell.setCellValue(legend.get(i));
            cell.setCellStyle(titleStyle);
        }
        // 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖
        CellStyle dataStyle = wb.createCellStyle();
        // 设置居中样式，水平居中
        dataStyle.setAlignment(HorizontalAlignment.CENTER);

        // 数据从序号1开始
        try {
            int index = 1;
            for (K value : list) {
                // 默认的行数从0开始，为了统一格式设置从1开始，就是从excel的第二行开始
                row = sheet.createRow(index);
                index++;
                for (int i = 0; i < columns.size(); i++) {
                    Cell cell = row.createCell(i);
                    // 为当前列赋值
                    String val = getKValue(columns.get(i), value);
                    if (columns.get(i).equals("status")) {
                        switch (val) {
                            case "-1":
                                val = languageManager.getLan().getUnknown();
                                break;
                            case "0":
                                val = languageManager.getLan().getRestored();
                                break;
                            case "1":
                                val = languageManager.getLan().getAlarmActive();
                                break;
                            default:
                                break;
                        }
                    }
                    if (columns.get(i).equals("alarmlevel")) {
                        switch (val) {
                            case "-1":
                                val = languageManager.getLan().getUnknown();
                                break;
                            case "0":
                                val = languageManager.getLan().getNormal();
                                break;
                            case "1":
                                val = languageManager.getLan().getWarning();
                                break;
                            case "2":
                                val = languageManager.getLan().getAlarm();
                                break;
                            default:
                                break;
                        }
                    }
                    // 断路器机械特性↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                    if (columns.get(i).equals("openorclose")) {
                        switch (val) {
                            case "0":
                                val = "分闸状态";
                                break;
                            case "1":
                                val = "合闸状态";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("storage")) {
                        switch (val) {
                            case "0":
                                val = "未储能";
                                break;
                            case "1":
                                val = "已储能";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("openingcircuit")) {
                        switch (val) {
                            case "0":
                                val = "正常";
                                break;
                            case "1":
                                val = "不能合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("closingcircuit")) {
                        switch (val) {
                            case "0":
                                val = "正常";
                                break;
                            case "1":
                                val = "不能分闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    // 消弧控制器↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                    if (columns.get(i).equals("ascp")) {
                        switch (val) {
                            case "0":
                                val = "分闸";
                                break;
                            case "1":
                                val = "合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("bscp")) {
                        switch (val) {
                            case "0":
                                val = "分闸";
                                break;
                            case "1":
                                val = "合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("cscp")) {
                        switch (val) {
                            case "0":
                                val = "分闸";
                                break;
                            case "1":
                                val = "合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("busclose")) {
                        switch (val) {
                            case "0":
                                val = "未联机";
                                break;
                            case "1":
                                val = "联机";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("isolate")) {
                        switch (val) {
                            case "0":
                                val = "分闸";
                                break;
                            case "1":
                                val = "合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    cell.setCellValue(val);
                    // 设置数据的样式
                    cell.setCellStyle(dataStyle);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * 导出实时表Excel
     * 
     * @param record
     * @return
     */
    public Workbook writeToExcelBySensorList(T record) {
        List<String> legend = new ArrayList<>();
        List<String> columns = new ArrayList<>();
        DefaultPropertyByInsert table = new DefaultPropertyByInsert();
        DefaultProperty table1 = new DefaultProperty();
        BeanUtils.copyProperties(record, table1);
        table.setStationid(table1.getStationid());
        table.setDevicegroup(table1.getDevicegroup());
        table.setDeviceaddr(table1.getDeviceaddr());
        table.setPointaddr(table1.getPointaddr());
        T t = newTclass(modelClass);
        BeanUtils.copyProperties(table, t);
        List<T> tlist = getLists(t);
        if (tlist.size() == 0) {
            return new XSSFWorkbook();
        } else {
            t = tlist.get(0);
        }
        BeanUtils.copyProperties(t, table);
        String[] leg = table.getStyle().split(",");
        columns.add("stationid");
        columns.add("devicegroup");
        columns.add("deviceaddr");
        if (table1.getPointaddr() != null) {
            columns.add("pointaddr");
        }
        columns.add("pointname");
        columns.add("lastdatatime");
        legend.add(languageManager.getLan().getStationID());
        legend.add(languageManager.getLan().getDeviceGroup());
        legend.add(languageManager.getLan().getDeviceAddress());
        if (table1.getPointaddr() != null) {
            legend.add(languageManager.getLan().getPointAddress());
        }
        legend.add(languageManager.getLan().getPointName());
        legend.add(languageManager.getLan().getDataTime());
        for (int i = 0; i < leg.length; i++) {
            if (leg[i].split("\\|")[1].equals("1")) {
                String[] ls = leg[i].split("\\|");
                if (getValueType("last" + ls[0], t) || getValueType(ls[0], t)) {
                    legend.add(ls[2]);
                    columns.add("last" + ls[0]);
                    if (ls[0].equals("simxbvoltage")) {

                    }
                }
            }
        }
        columns.add("lastalarmlevel");
        columns.add("lastalarmmessage");
        legend.add(languageManager.getLan().getAlarmLevel());
        legend.add(languageManager.getLan().getAlarmDetails());
        List<T> list = new ArrayList<>();
        Example example = ConditionDispose.defaultDisposeByInUse(record, record.getClass());
        list = selectByExample(example);

        // 创建工作薄
        Workbook wb = new XSSFWorkbook();
        // 标题和页码
        CellStyle titleStyle = wb.createCellStyle();
        // 设置单元格对齐方式,水平居左
        titleStyle.setAlignment(HorizontalAlignment.LEFT);
        // 设置字体样式
        Font titleFont = wb.createFont();
        // 字体高度
        titleFont.setFontHeightInPoints((short) 12);
        // 字体样式
        titleFont.setFontName("黑体");
        titleStyle.setFont(titleFont);
        // 创建sheet
        Sheet sheet = wb.createSheet(languageManager.getLan().getRealtimeDetails());
        // 自动设置宽度
        sheet.autoSizeColumn(0);

        // 在sheet中添加标题行// 行数从0开始
        Row row = sheet.createRow((int) 0);
        for (int i = 0; i < legend.size(); i++) {
            if (legend.get(i).equals(languageManager.getLan().getDataTime())) {
                sheet.setColumnWidth(i, 5000);
            }
            Cell cell = row.createCell(i);
            cell.setCellValue(legend.get(i));
            cell.setCellStyle(titleStyle);
        }
        // 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖
        CellStyle dataStyle = wb.createCellStyle();
        // 设置居中样式，水平居中
        dataStyle.setAlignment(HorizontalAlignment.CENTER);

        // 数据从序号1开始
        try {
            int index = 1;
            for (T value : list) {
                // 默认的行数从0开始，为了统一格式设置从1开始，就是从excel的第二行开始
                row = sheet.createRow(index);
                index++;
                for (int i = 0; i < columns.size(); i++) {
                    Cell cell = row.createCell(i);
                    // 为当前列赋值
                    String val = getTValue(columns.get(i), value);

                    if (columns.get(i).equals("status") || columns.get(i).equals("lastcommunicationstatus")) {
                        switch (val) {
                            case "-1":
                                val = languageManager.getLan().getUnknown();
                                break;
                            case "0":
                                val = languageManager.getLan().getRestored();
                                break;
                            case "1":
                                val = languageManager.getLan().getAlarmActive();
                                break;
                            default:
                                break;
                        }
                    }
                    if (columns.get(i).equals("alarmlevel") || columns.get(i).equals("lastalarmlevel")) {
                        if (val == null) {
                            val = languageManager.getLan().getNormal();
                            break;
                        } else {
                            switch (val) {
                                case "-1":
                                    val = languageManager.getLan().getUnknown();
                                    break;
                                case "0":
                                    val = languageManager.getLan().getNormal();
                                    break;
                                case "1":
                                    val = languageManager.getLan().getWarning();
                                    break;
                                case "2":
                                    val = languageManager.getLan().getAlarm();
                                    break;
                                default:
                                    break;
                            }
                        }

                    }
                    // 断路器机械特性↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                    if (columns.get(i).equals("lastopenorclose")) {
                        if (val == null) {
                            val = "未知";
                            break;
                        } else {
                            switch (val) {
                                case "0":
                                    val = "分闸状态";
                                    break;
                                case "1":
                                    val = "合闸状态";
                                    break;
                                default:
                                    val = "未知";
                                    break;
                            }
                        }
                    }
                    // 断路器↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                    if (columns.get(i).equals("lastastate") || columns.get(i).equals("lastbstate")
                            || columns.get(i).equals("lastcstate")) {
                        if (val == null) {
                            val = "未知";
                            break;
                        } else {
                            switch (val) {
                                case "0":
                                    val = "分闸状态";
                                    break;
                                case "1":
                                    val = "合闸状态";
                                    break;
                                default:
                                    val = "未知";
                                    break;
                            }
                        }
                    }
                    if (columns.get(i).equals("lastastoragestate") || columns.get(i).equals("lastbstoragestate")
                            || columns.get(i).equals("lastcstoragestate")) {
                        if (val == null) {
                            val = "未知";
                            break;
                        } else {
                            switch (val) {
                                case "0":
                                    val = "未储能";
                                    break;
                                case "1":
                                    val = "已储能";
                                    break;
                                default:
                                    val = "未知";
                                    break;
                            }
                        }
                    }
                    if (columns.get(i).equals("lastacount")) {
                        val = getTValue("acount", value);
                    }
                    if (columns.get(i).equals("lastbcount")) {
                        val = getTValue("bcount", value);
                    }
                    if (columns.get(i).equals("lastccount")) {
                        val = getTValue("ccount", value);
                    }
                    if (columns.get(i).equals("laststorage")) {
                        switch (val) {
                            case "0":
                                val = "未储能";
                                break;
                            case "1":
                                val = "已储能";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("lastopeningcircuit")) {
                        switch (val) {
                            case "0":
                                val = "正常";
                                break;
                            case "1":
                                val = "不能合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("lastclosingcircuit")) {
                        switch (val) {
                            case "0":
                                val = "正常";
                                break;
                            case "1":
                                val = "不能分闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    // 消弧控制器↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                    if (columns.get(i).equals("lastascp")) {
                        switch (val) {
                            case "0":
                                val = "分闸";
                                break;
                            case "1":
                                val = "合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("lastbscp")) {
                        switch (val) {
                            case "0":
                                val = "分闸";
                                break;
                            case "1":
                                val = "合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("lastcscp")) {
                        switch (val) {
                            case "0":
                                val = "分闸";
                                break;
                            case "1":
                                val = "合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("lastbusclose")) {
                        switch (val) {
                            case "0":
                                val = "未联机";
                                break;
                            case "1":
                                val = "联机";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    if (columns.get(i).equals("lastisolate")) {
                        switch (val) {
                            case "0":
                                val = "分闸";
                                break;
                            case "1":
                                val = "合闸";
                                break;
                            default:
                                val = "未知";
                                break;
                        }
                    }
                    cell.setCellValue(val);
                    // 设置数据的样式
                    cell.setCellStyle(dataStyle);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * 实例化T
     * 
     * @param <T>
     * @param clazz
     * @return
     */
    static <T> T newTclass(Class<T> clazz) {
        T obj = null;
        try {
            obj = clazz.getDeclaredConstructor().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
